<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>积分中心 - 积分商城</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 核心工具库 -->
    <script src="../../js/core.js"></script>
    <!-- 购物车相关函数 -->
    <script>
        // 购物车相关函数
        function getCart() {
            const cartStr = localStorage.getItem('cart');
            return cartStr ? JSON.parse(cartStr) : [];
        }
        
        function decreaseQuantity(productId) {
            const cart = getCart();
            const item = cart.find(i => i.id === productId);
            if (item && item.quantity > 1) {
                item.quantity--;
            } else if (item && item.quantity === 1) {
                removeFromCart(productId);
                return;
            }
            localStorage.setItem('cart', JSON.stringify(cart));
        }
        
        function increaseQuantity(productId) {
            const cart = getCart();
            const item = cart.find(i => i.id === productId);
            if (item) {
                item.quantity++;
                localStorage.setItem('cart', JSON.stringify(cart));
            }
        }
        
        function removeFromCart(productId) {
            const cart = getCart();
            const newCart = cart.filter(item => item.id !== productId);
            localStorage.setItem('cart', JSON.stringify(newCart));
        }
        
        // 积分历史记录函数
        function getPointsHistory() {
            const historyStr = localStorage.getItem('pointsHistory');
            return historyStr ? JSON.parse(historyStr) : [];
        }
        
        // 通知函数
        function showNotification(title, message, type = 'info') {
            // 简单的通知实现
            console.log(`${type.toUpperCase()}: ${title} - ${message}`);
            // 可以扩展为更复杂的通知组件
        }
    </script>
    
    <!-- Tailwind 配置 - 移到Tailwind CSS加载之后 -->
    <script>
        // Tailwind配置
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2E7D32',
                        secondary: '#FFC107',
                        dark: '#1B5E20',
                        light: '#E8F5E9',
                        accent: '#4CAF50',
                        danger: '#D32F2F'
                    },
                    fontFamily: {
                        sans: ['Roboto', 'sans-serif']
                    },
                    backgroundImage: {
                        'pattern': "url('images/bg-pattern.png')",
                    }
                },
            }
        }
    </script>
    
    <!-- CSS 文件拆分引入 -->
    <link rel="stylesheet" href="../../css/base.css">
    <link rel="stylesheet" href="../../css/layout.css">
    <link rel="stylesheet" href="../../css/components.css">
    <!-- 移除可能有问题的CSS引用 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .task-card-shadow {
                @apply shadow-md hover:shadow-lg transition-shadow duration-300;
            }
            .points-badge {
                @apply inline-flex items-center justify-center px-2 py-1 rounded-full text-xs font-medium;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <nav id="navbar" class="bg-white shadow-sm sticky top-0 z-40">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-shopping-bag text-primary text-2xl"></i>
                <a href="../../index.html" class="text-xl font-bold text-primary">积分商城</a>
            </div>
            
            <div class="hidden md:flex items-center space-x-6">
                <a href="../../index.html" class="text-dark hover:text-primary transition-colors">首页</a>
                <a href="shop.html" class="text-dark hover:text-primary transition-colors">商城</a>
                <a href="points.html" class="text-primary font-medium">积分中心</a>
            </div>
            
            <div class="flex items-center space-x-4">
                <div class="relative">
                    <input type="text" placeholder="搜索商品" class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary w-48 md:w-64">
                    <i class="fa fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
                
                <button id="cart-btn" class="relative p-2 text-dark hover:text-primary transition-colors">
                    <i class="fa fa-shopping-cart text-xl"></i>
                    <span id="cart-count" class="absolute -top-1 -right-1 bg-danger text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">0</span>
                </button>
                
                <div id="user-menu" class="relative">
                    <button id="user-menu-btn" class="flex items-center space-x-2">
                        <div id="avatar-placeholder" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                            <i class="fa fa-user text-gray-500"></i>
                        </div>
                        <span id="user-name" class="hidden md:inline-block text-dark">登录/注册</span>
                        <i class="fa fa-angle-down text-gray-500"></i>
                    </button>
                    <div id="user-dropdown" class="hidden absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg z-50">
                        <div id="login-register" class="p-4">
                            <p class="text-sm text-gray-600 mb-2">请登录以使用更多功能</p>
                            <div class="flex space-x-2">
                                <a href="../user/login.html" class="flex-1 text-center py-1 px-2 text-sm bg-gray-100 hover:bg-gray-200 rounded transition-colors">登录</a>
                                <a href="../user/register.html" class="flex-1 text-center py-1 px-2 text-sm bg-primary text-white hover:bg-primary/90 rounded transition-colors">注册</a>
                            </div>
                        </div>
                        <div id="user-info" class="hidden">
                            <div class="p-3 border-b">
                                <div class="flex items-center space-x-2">
                                    <img id="user-avatar" src="" alt="用户头像" class="w-8 h-8 rounded-full">
                                    <div>
                                        <p id="dropdown-username" class="text-sm font-medium"></p>
                                        <p id="dropdown-userpoints" class="text-xs text-primary"></p>
                                    </div>
                                </div>
                            </div>
                            <a href="../user/user-center.html" class="block px-4 py-2 text-sm hover:bg-gray-50">个人中心</a>
                            <a href="orders.html" class="block px-4 py-2 text-sm hover:bg-gray-50">我的订单</a>
                            <a href="points.html" class="block px-4 py-2 text-sm hover:bg-gray-50">我的积分</a>
                            <button id="logout-btn" class="block w-full text-left px-4 py-2 text-sm text-danger hover:bg-gray-50">退出登录</button>
                        </div>
                    </div>
                </div>
                
                <button id="mobile-menu-btn" class="md:hidden p-2 text-dark hover:text-primary transition-colors">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
        
        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="hidden md:hidden bg-white border-t">
            <div class="container mx-auto px-4 py-3 flex flex-col space-y-4">
                <a href="../../index.html" class="text-dark hover:text-primary transition-colors py-2 border-b border-gray-100">首页</a>
                <a href="shop.html" class="text-dark hover:text-primary transition-colors py-2 border-b border-gray-100">商城</a>
                <a href="points.html" class="text-primary font-medium py-2">积分中心</a>
                <div class="relative py-2">
                    <input type="text" placeholder="搜索商品" class="w-full pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                    <i class="fa fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
            </div>
        </div>
    </nav>

    <!-- 面包屑导航 -->
    <div class="bg-white border-b">
        <div class="container mx-auto px-4 py-2">
            <div class="flex items-center text-sm">
                <a href="../../index.html" class="text-gray-500 hover:text-primary transition-colors">首页</a>
                <i class="fa fa-angle-right text-gray-400 mx-2"></i>
                <span class="text-dark">积分中心</span>
            </div>
        </div>
    </div>

    <!-- 主要内容 -->
    <main class="flex-1">
        <!-- 积分概览卡片 -->
        <div class="container mx-auto px-4 py-8">
            <div id="not-logged-in" class="bg-white rounded-2xl shadow-lg p-8 text-center">
                <i class="fa fa-user-circle text-gray-300 text-6xl mb-4"></i>
                <h3 class="text-xl font-medium mb-2">您还未登录</h3>
                <p class="text-gray-500 mb-6">登录后可以查看您的积分信息和完成积分任务</p>
                <div class="flex justify-center space-x-4">
                    <a href="../user/login.html" class="px-6 py-3 bg-gray-100 text-dark rounded-lg hover:bg-gray-200 transition-colors font-medium">登录</a>
                    <a href="../user/register.html" class="px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium">注册</a>
                </div>
            </div>

            <div id="user-points-overview" class="hidden">
                <div class="gradient-bg text-white rounded-2xl shadow-lg p-8 mb-8">
                    <div class="flex flex-col md:flex-row justify-between items-center">
                        <div class="mb-6 md:mb-0">
                            <h2 class="text-2xl font-bold mb-2">我的积分</h2>
                            <p class="opacity-80">积分可以兑换商品、参与活动</p>
                        </div>
                        <div class="text-center md:text-right">
                            <div class="text-4xl font-bold mb-2" id="user-total-points">0</div>
                            <div class="flex flex-wrap justify-center md:justify-end space-x-2 mt-4">
                                <button id="check-history-btn" class="px-3 py-1.5 bg-white/20 hover:bg-white/30 transition-colors rounded-lg text-sm">
                                    <i class="fa fa-history mr-1"></i>查看明细
                                </button>
                                <button id="points-recharge-btn" class="px-3 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm">
                                    <i class="fa fa-plus-circle mr-1"></i>积分充值
                                </button>
                                <button id="points-exchange-btn" class="px-3 py-1.5 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-colors text-sm">
                                    <i class="fa fa-exchange mr-1"></i>积分兑换
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-8">
                        <div class="bg-white/10 rounded-xl p-4 text-center">
                            <div class="text-xl font-bold mb-1" id="available-points">0</div>
                            <div class="text-sm opacity-80">可用积分</div>
                        </div>
                        <div class="bg-white/10 rounded-xl p-4 text-center">
                            <div class="text-xl font-bold mb-1" id="used-points">0</div>
                            <div class="text-sm opacity-80">已用积分</div>
                        </div>
                        <div class="bg-white/10 rounded-xl p-4 text-center">
                            <div class="text-xl font-bold mb-1" id="expired-points">0</div>
                            <div class="text-sm opacity-80">即将过期</div>
                        </div>
                    </div>
                </div>

                <!-- 每日签到 -->
                <div class="bg-white rounded-2xl shadow-lg p-6 mb-8">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-lg font-bold">每日签到</h3>
                        <span class="text-sm text-gray-500" id="sign-in-status">今日已签到</span>
                    </div>
                    
                    <div class="flex flex-col md:flex-row items-center justify-between">
                        <div class="flex space-x-2 mb-4 md:mb-0">
                            <div class="w-16 h-16 rounded-full bg-success/10 flex items-center justify-center text-success text-xl font-bold">
                                <i class="fa fa-calendar-check-o"></i>
                            </div>
                            <div>
                                <p class="text-gray-600">连续签到 <span class="text-primary font-medium" id="consecutive-days">0</span> 天</p>
                                <p class="text-sm text-gray-500">再签到 <span class="text-primary">3</span> 天获得额外奖励</p>
                            </div>
                        </div>
                        
                        <button id="sign-in-btn" class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed">
                            <i class="fa fa-sign-in mr-1"></i>立即签到
                        </button>
                    </div>
                </div>

                <!-- 积分任务 -->
                <div class="bg-white rounded-2xl shadow-lg p-6 mb-8">
                    <h3 class="text-lg font-bold mb-6">积分任务</h3>
                    
                    <div class="space-y-4">
                        <!-- 每日任务 -->
                        <div class="task-card bg-gray-50 rounded-xl p-4">
                            <h4 class="text-md font-medium mb-3">每日任务</h4>
                            <div class="space-y-3">
                                <div class="task-item flex items-center justify-between p-3 bg-white rounded-lg task-card-shadow">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                            <i class="fa fa-refresh"></i>
                                        </div>
                                        <div>
                                            <p class="font-medium">浏览商城 5 分钟</p>
                                            <p class="text-sm text-gray-500">奖励 10 积分</p>
                                        </div>
                                    </div>
                                    <button class="task-action-btn px-4 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm" data-task="daily-browse">
                                        去完成
                                    </button>
                                </div>
                                <div class="task-item flex items-center justify-between p-3 bg-white rounded-lg task-card-shadow">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                            <i class="fa fa-search"></i>
                                        </div>
                                        <div>
                                            <p class="font-medium">搜索商品 3 次</p>
                                            <p class="text-sm text-gray-500">奖励 5 积分</p>
                                        </div>
                                    </div>
                                    <button class="task-action-btn px-4 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm" data-task="daily-search">
                                        去完成
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 新手任务 -->
                        <div class="task-card bg-gray-50 rounded-xl p-4">
                            <h4 class="text-md font-medium mb-3">新手任务</h4>
                            <div class="space-y-3">
                                <div class="task-item flex items-center justify-between p-3 bg-white rounded-lg task-card-shadow">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                            <i class="fa fa-user-plus"></i>
                                        </div>
                                        <div>
                                            <p class="font-medium">完善个人资料</p>
                                            <p class="text-sm text-gray-500">奖励 50 积分</p>
                                        </div>
                                    </div>
                                    <button class="task-action-btn px-4 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm" data-task="complete-profile">
                                        去完成
                                    </button>
                                </div>
                                <div class="task-item flex items-center justify-between p-3 bg-white rounded-lg task-card-shadow">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                            <i class="fa fa-star"></i>
                                        </div>
                                        <div>
                                            <p class="font-medium">首次收藏商品</p>
                                            <p class="text-sm text-gray-500">奖励 20 积分</p>
                                        </div>
                                    </div>
                                    <button class="task-action-btn px-4 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm" data-task="first-favorite">
                                        去完成
                                    </button>
                                </div>
                                <div class="task-item flex items-center justify-between p-3 bg-white rounded-lg task-card-shadow">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                            <i class="fa fa-shopping-cart"></i>
                                        </div>
                                        <div>
                                            <p class="font-medium">首次兑换商品</p>
                                            <p class="text-sm text-gray-500">奖励 100 积分</p>
                                        </div>
                                    </div>
                                    <button class="task-action-btn px-4 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm" data-task="first-exchange">
                                        去完成
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 成长任务 -->
                        <div class="task-card bg-gray-50 rounded-xl p-4">
                            <h4 class="text-md font-medium mb-3">成长任务</h4>
                            <div class="space-y-3">
                                <div class="task-item flex items-center justify-between p-3 bg-white rounded-lg task-card-shadow">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                            <i class="fa fa-calendar"></i>
                                        </div>
                                        <div>
                                            <p class="font-medium">连续签到 7 天</p>
                                            <p class="text-sm text-gray-500">奖励 50 积分</p>
                                        </div>
                                    </div>
                                    <button class="task-action-btn px-4 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm" data-task="weekly-checkin">
                                        去完成
                                    </button>
                                </div>
                                <div class="task-item flex items-center justify-between p-3 bg-white rounded-lg task-card-shadow">
                                    <div class="flex items-center space-x-3">
                                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                            <i class="fa fa-users"></i>
                                        </div>
                                        <div>
                                            <p class="font-medium">邀请好友注册</p>
                                            <p class="text-sm text-gray-500">奖励 20 积分/人</p>
                                        </div>
                                    </div>
                                    <button class="task-action-btn px-4 py-1.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm" data-task="invite-friends">
                                        去邀请
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 积分攻略 -->
                <div class="bg-white rounded-2xl shadow-lg p-6 mb-8">
                    <h3 class="text-lg font-bold mb-4">积分攻略</h3>
                    <div class="space-y-4">
                        <div class="p-4 border border-gray-100 rounded-lg">
                            <div class="flex items-center space-x-2 mb-2">
                                <i class="fa fa-lightbulb-o text-warning"></i>
                                <h4 class="font-medium">如何获得积分？</h4>
                            </div>
                            <ul class="text-sm text-gray-600 space-y-2">
                                <li class="flex items-start">
                                    <i class="fa fa-check-circle text-success mt-1 mr-2"></i>
                                    <span>每日签到可获得 5-20 积分，连续签到积分递增</span>
                                </li>
                                <li class="flex items-start">
                                    <i class="fa fa-check-circle text-success mt-1 mr-2"></i>
                                    <span>完成积分任务可获得对应积分奖励</span>
                                </li>
                                <li class="flex items-start">
                                    <i class="fa fa-check-circle text-success mt-1 mr-2"></i>
                                    <span>邀请好友注册并完成首单可获得额外奖励</span>
                                </li>
                            </ul>
                        </div>
                        <div class="p-4 border border-gray-100 rounded-lg">
                            <div class="flex items-center space-x-2 mb-2">
                                <i class="fa fa-info-circle text-primary"></i>
                                <h4 class="font-medium">积分有效期</h4>
                            </div>
                            <p class="text-sm text-gray-600">积分有效期为一年，从获得积分之日起计算，逾期未使用的积分将自动清零。请及时查看您的积分明细，合理规划使用。</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 积分充值弹窗 -->
    <div id="points-recharge-modal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white w-full max-w-md rounded-2xl shadow-xl transform transition-all duration-300 max-h-[80vh] overflow-hidden flex flex-col">
            <div class="p-5 border-b flex justify-between items-center sticky top-0 bg-white z-10">
                <h3 class="font-bold text-lg">积分充值</h3>
                <button id="close-recharge-modal" class="p-2 text-gray-500 hover:text-dark transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-5 flex-1 overflow-y-auto">
                <div class="mb-5">
                    <label class="block text-gray-700 text-sm font-medium mb-2" for="recharge-amount">
                        充值积分数量
                    </label>
                    <input type="number" id="recharge-amount" min="1" step="1" placeholder="请输入整数积分数量" 
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                    <p class="text-xs text-gray-500 mt-1">请输入您要充值的积分数量（仅限整数）</p>
                </div>
                <div class="mb-5">
                    <p class="text-sm text-gray-700 font-medium mb-2">当前积分：<span id="current-points-display" class="text-primary font-bold">0</span></p>
                    <p class="text-sm text-gray-700 font-medium mb-2">充值后积分：<span id="after-recharge-points" class="text-primary font-bold">0</span></p>
                </div>
            </div>
            <div class="p-5 border-t">
                <button id="confirm-recharge-btn" class="w-full py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium">
                    确认充值
                </button>
            </div>
        </div>
    </div>

    <!-- 积分兑换弹窗 -->
    <div id="points-exchange-modal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white w-full max-w-md rounded-2xl shadow-xl transform transition-all duration-300 max-h-[80vh] overflow-hidden flex flex-col">
            <div class="p-5 border-b flex justify-between items-center sticky top-0 bg-white z-10">
                <h3 class="font-bold text-lg">积分兑换</h3>
                <button id="close-exchange-modal" class="p-2 text-gray-500 hover:text-dark transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-5 flex-1 overflow-y-auto">
                <div class="mb-5">
                    <label class="block text-gray-700 text-sm font-medium mb-2" for="exchange-amount">
                        兑换积分数量
                    </label>
                    <input type="number" id="exchange-amount" min="1" step="1" placeholder="请输入整数积分数量" 
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                    <p class="text-xs text-gray-500 mt-1">请输入您要兑换的积分数量（仅限整数）</p>
                </div>
                <div class="mb-5">
                    <p class="text-sm text-gray-700 font-medium mb-2">当前积分：<span id="exchange-current-points" class="text-primary font-bold">0</span></p>
                    <p class="text-sm text-gray-700 font-medium mb-2">兑换后积分：<span id="after-exchange-points" class="text-primary font-bold">0</span></p>
                </div>
            </div>
            <div class="p-5 border-t">
                <button id="confirm-exchange-btn" class="w-full py-3 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-colors font-medium">
                    确认兑换
                </button>
            </div>
        </div>
    </div>

    <!-- 积分明细弹窗 -->
    <div id="points-history-modal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white w-full max-w-2xl rounded-2xl shadow-xl transform transition-all duration-300 max-h-[80vh] overflow-hidden flex flex-col">
            <div class="p-5 border-b flex justify-between items-center sticky top-0 bg-white z-10">
                <h3 class="font-bold text-lg">积分明细</h3>
                <button id="close-history-modal" class="p-2 text-gray-500 hover:text-dark transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <div class="p-5 border-b">
                <div class="flex items-center justify-between mb-3">
                    <div>
                        <p class="text-sm text-gray-500">当前积分</p>
                        <p class="text-xl font-bold text-primary" id="history-modal-total-points">0</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">本月获得</p>
                        <p class="text-xl font-bold text-success" id="history-modal-monthly-gained">0</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">本月使用</p>
                        <p class="text-xl font-bold text-danger" id="history-modal-monthly-used">0</p>
                    </div>
                </div>
                
                <div class="flex space-x-2">
                    <button class="points-filter-btn flex-1 py-2 px-4 text-sm font-medium rounded-lg bg-primary text-white transition-colors" data-filter="all">
                        全部
                    </button>
                    <button class="points-filter-btn flex-1 py-2 px-4 text-sm font-medium rounded-lg bg-gray-100 hover:bg-gray-200 transition-colors" data-filter="gained">
                        获得
                    </button>
                    <button class="points-filter-btn flex-1 py-2 px-4 text-sm font-medium rounded-lg bg-gray-100 hover:bg-gray-200 transition-colors" data-filter="used">
                        使用
                    </button>
                </div>
            </div>
            
            <div id="points-history-content" class="flex-1 overflow-y-auto p-5">
                <div class="space-y-4" id="points-history-list">
                    <!-- 积分明细将通过 JavaScript 动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 购物车弹窗 -->
    <div id="cart-modal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-end justify-center">
        <div class="bg-white w-full max-w-3xl rounded-t-2xl shadow-2xl transform transition-transform duration-300 max-h-[80vh] overflow-hidden flex flex-col">
            <div class="p-5 border-b flex justify-between items-center sticky top-0 bg-white z-10">
                <h3 class="font-bold text-lg">我的购物车</h3>
                <button id="close-cart" class="p-2 text-gray-500 hover:text-dark transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <div id="cart-items" class="flex-1 overflow-y-auto p-5">
                <!-- 购物车为空时显示 -->
                <div id="cart-empty" class="text-center py-10">
                    <i class="fa fa-shopping-cart text-gray-300 text-5xl mb-4"></i>
                    <p class="text-gray-500 mb-4">购物车还是空的哦</p>
                    <a href="shop.html" class="inline-block px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">去逛逛</a>
                </div>
                
                <!-- 购物车商品列表 -->
                <div id="cart-items-list" class="space-y-4 hidden">
                    <!-- 购物车商品将通过 JavaScript 动态生成 -->
                </div>
            </div>
            
            <div class="p-5 border-t bg-gray-50 sticky bottom-0">
                <div class="flex justify-between items-center mb-4">
                    <div class="text-sm text-gray-600">
                        共 <span id="cart-items-count">0</span> 件商品
                    </div>
                    <div class="text-right">
                        <div class="text-sm text-gray-600">
                            总计积分：
                            <span id="cart-total-points" class="text-primary font-bold text-xl">0</span>
                        </div>
                    </div>
                </div>
                <button id="checkout-btn" class="w-full py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium" disabled>
                    去结算
                </button>
            </div>
        </div>
    </div>

    <!-- 通知弹窗 -->
    <div id="notification" class="fixed top-20 right-4 bg-white shadow-lg rounded-lg p-4 max-w-xs transform translate-x-full transition-transform duration-300 z-50 hidden">
        <div class="flex items-start space-x-3">
            <div id="notification-icon" class="w-8 h-8 rounded-full flex items-center justify-center bg-primary/10 text-primary">
                <i class="fa fa-info-circle"></i>
            </div>
            <div class="flex-1">
                <h4 id="notification-title" class="font-medium text-dark"></h4>
                <p id="notification-message" class="text-gray-600 text-sm mt-1"></p>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-dark text-white py-12">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div>
                    <div class="flex items-center space-x-2 mb-4">
                        <i class="fa fa-shopping-bag text-primary text-2xl"></i>
                        <span class="text-xl font-bold">积分商城</span>
                    </div>
                    <p class="text-gray-400 text-sm mb-4">积分商城是一个专注于积分兑换和会员福利的平台，为用户提供丰富多彩的商品和服务。</p>
                    <div class="flex space-x-4">
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-weibo"></i>
                        </a>
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-weixin"></i>
                        </a>
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-qq"></i>
                        </a>
                    </div>
                </div>
                <div>
                    <h4 class="text-lg font-medium mb-4">快速链接</h4>
                    <ul class="space-y-2 text-gray-400">
                        <li><a href="../../index.html" class="hover:text-primary transition-colors">首页</a></li>
                        <li><a href="shop.html" class="hover:text-primary transition-colors">商城</a></li>
                        <li><a href="points.html" class="hover:text-primary transition-colors">积分中心</a></li>
                        <li><a href="about.html" class="hover:text-primary transition-colors">关于我们</a></li>
                    </ul>
                </div>
                <div>
                    <h4 class="text-lg font-medium mb-4">帮助中心</h4>
                    <ul class="space-y-2 text-gray-400">
                        <li><a href="faq.html" class="hover:text-primary transition-colors">常见问题</a></li>
                        <li><a href="terms.html" class="hover:text-primary transition-colors">用户协议</a></li>
                        <li><a href="privacy.html" class="hover:text-primary transition-colors">隐私政策</a></li>
                        <li><a href="contact.html" class="hover:text-primary transition-colors">联系我们</a></li>
                    </ul>
                </div>
                <div>
                    <h4 class="text-lg font-medium mb-4">联系我们</h4>
                    <ul class="space-y-2 text-gray-400">
                        <li class="flex items-start">
                            <i class="fa fa-map-marker mt-1 mr-3"></i>
                            <span>北京市朝阳区建国路88号</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-phone mr-3"></i>
                            <span>400-123-4567</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-envelope mr-3"></i>
                            <span>support@points-mall.com</span>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="border-t border-gray-800 mt-8 pt-8 text-center text-gray-500 text-sm">
                <p>© 2023 积分商城. 保留所有权利。</p>
            </div>
        </div>
    </footer>

    <!-- 工具函数已在页面头部内联实现 -->
    <script>
        // 移动端菜单切换
        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
        const mobileMenu = document.getElementById('mobile-menu');
        
        if (mobileMenuBtn && mobileMenu) {
            mobileMenuBtn.addEventListener('click', () => {
                mobileMenu.classList.toggle('hidden');
            });
        }

        // 购物车弹窗
        const cartBtn = document.getElementById('cart-btn');
        const cartModal = document.getElementById('cart-modal');
        const closeCart = document.getElementById('close-cart');
        const cartItems = document.getElementById('cart-items');
        const cartEmpty = document.getElementById('cart-empty');
        const cartItemsList = document.getElementById('cart-items-list');
        const cartItemsCount = document.getElementById('cart-items-count');
        const cartTotalPoints = document.getElementById('cart-total-points');
        const checkoutBtn = document.getElementById('checkout-btn');
        const cartCount = document.getElementById('cart-count');
        
        if (cartBtn && cartModal) {
            cartBtn.addEventListener('click', () => {
                // 更新购物车内容
                updateCartDisplay();
                // 显示购物车弹窗
                cartModal.classList.remove('hidden');
            });
        }
        
        if (closeCart && cartModal) {
            closeCart.addEventListener('click', () => {
                cartModal.classList.add('hidden');
            });
        }
        
        if (cartModal) {
            cartModal.addEventListener('click', (e) => {
                if (e.target === cartModal) {
                    cartModal.classList.add('hidden');
                }
            });
        }

        // 用户菜单
        const userMenuBtn = document.getElementById('user-menu-btn');
        const userDropdown = document.getElementById('user-dropdown');
        const loginRegister = document.getElementById('login-register');
        const userInfo = document.getElementById('user-info');
        const userName = document.getElementById('user-name');
        const avatarPlaceholder = document.getElementById('avatar-placeholder');
        const userAvatar = document.getElementById('user-avatar');
        const dropdownUsername = document.getElementById('dropdown-username');
        const dropdownUserpoints = document.getElementById('dropdown-userpoints');
        const logoutBtn = document.getElementById('logout-btn');
        
        if (userMenuBtn && userDropdown) {
            userMenuBtn.addEventListener('click', () => {
                userDropdown.classList.toggle('hidden');
            });
        }
        
        // 点击其他地方关闭下拉菜单
        document.addEventListener('click', (e) => {
            if (userDropdown && !userMenuBtn.contains(e.target) && !userDropdown.contains(e.target)) {
                userDropdown.classList.add('hidden');
            }
        });
        
        // 退出登录
        if (logoutBtn) {
            logoutBtn.addEventListener('click', () => {
                logout();
                updateUserDisplay();
                showNotification('退出成功', '您已成功退出登录', 'info');
            });
        }

        // 积分明细弹窗
        const checkHistoryBtn = document.getElementById('check-history-btn');
        const pointsHistoryModal = document.getElementById('points-history-modal');
        const closeHistoryModal = document.getElementById('close-history-modal');
        const pointsHistoryList = document.getElementById('points-history-list');
        const pointsFilterBtns = document.querySelectorAll('.points-filter-btn');
        const historyModalTotalPoints = document.getElementById('history-modal-total-points');
        const historyModalMonthlyGained = document.getElementById('history-modal-monthly-gained');
        const historyModalMonthlyUsed = document.getElementById('history-modal-monthly-used');
        
        if (checkHistoryBtn && pointsHistoryModal) {
            checkHistoryBtn.addEventListener('click', () => {
                updatePointsHistory();
                pointsHistoryModal.classList.remove('hidden');
            });
        }
        
        if (closeHistoryModal && pointsHistoryModal) {
            closeHistoryModal.addEventListener('click', () => {
                pointsHistoryModal.classList.add('hidden');
            });
        }
        
        if (pointsHistoryModal) {
            pointsHistoryModal.addEventListener('click', (e) => {
                if (e.target === pointsHistoryModal) {
                    pointsHistoryModal.classList.add('hidden');
                }
            });
        }
        
        // 积分筛选
        pointsFilterBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                pointsFilterBtns.forEach(b => {
                    b.classList.remove('bg-primary', 'text-white');
                    b.classList.add('bg-gray-100', 'hover:bg-gray-200');
                });
                this.classList.remove('bg-gray-100', 'hover:bg-gray-200');
                this.classList.add('bg-primary', 'text-white');
                updatePointsHistory(this.dataset.filter);
            });
        });

        // 每日签到
        const signInBtn = document.getElementById('sign-in-btn');
        const signInStatus = document.getElementById('sign-in-status');
        const consecutiveDays = document.getElementById('consecutive-days');
        
        if (signInBtn) {
            signInBtn.addEventListener('click', () => {
                const userInfoData = getUserInfo();
                if (userInfoData) {
                    const today = new Date().toDateString();
                    const lastSignIn = localStorage.getItem('lastSignIn');
                    const currentConsecutive = parseInt(localStorage.getItem('consecutiveSignInDays') || '0');
                    
                    if (lastSignIn !== today) {
                        // 签到积分计算
                        let pointsReward = 5 + Math.min(currentConsecutive * 2, 15);
                        
                        // 连续签到奖励
                        if (currentConsecutive > 0 && currentConsecutive % 7 === 0) {
                            pointsReward += 50; // 连续7天额外奖励50积分
                        }
                        
                        // 更新用户积分
                        userInfoData.points = (userInfoData.points || 0) + pointsReward;
                        setUserInfo(userInfoData);
                        
                        // 更新签到记录
                        localStorage.setItem('lastSignIn', today);
                        
                        // 更新连续签到天数
                        let newConsecutiveDays = 1;
                        if (lastSignIn) {
                            const yesterday = new Date();
                            yesterday.setDate(yesterday.getDate() - 1);
                            if (lastSignIn === yesterday.toDateString()) {
                                newConsecutiveDays = currentConsecutive + 1;
                            }
                        }
                        localStorage.setItem('consecutiveSignInDays', newConsecutiveDays.toString());
                        
                        // 添加积分记录
                        addPointsRecord(pointsReward, '每日签到', 'gained');
                        
                        // 更新UI
                        updateUserDisplay();
                        updatePointsHistory();
                        signInStatus.textContent = '今日已签到';
                        signInBtn.disabled = true;
                        consecutiveDays.textContent = newConsecutiveDays;
                        
                        showNotification('签到成功', `获得 ${pointsReward} 积分奖励`, 'success');
                    } else {
                        showNotification('提示', '您今天已经签到过了', 'info');
                    }
                } else {
                    window.location.href = 'login.html';
                }
            });
        }

        // 任务按钮点击事件
        const taskActionBtns = document.querySelectorAll('.task-action-btn');
        taskActionBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                const task = this.dataset.task;
                const userInfoData = getUserInfo();
                
                if (!userInfoData) {
                    window.location.href = 'login.html';
                    return;
                }
                
                switch (task) {
                    case 'daily-browse':
                        window.location.href = 'shop.html';
                        // 模拟浏览5分钟后获得积分
                        setTimeout(() => {
                            // 这里只是模拟，实际应用中需要更复杂的逻辑来检测用户行为
                            showNotification('任务完成', '您已完成浏览商城任务，获得10积分', 'success');
                        }, 1000);
                        break;
                    case 'daily-search':
                        window.location.href = 'shop.html';
                        break;
                    case 'complete-profile':
                        window.location.href = 'user-center.html';
                        break;
                    case 'first-favorite':
                        window.location.href = 'shop.html';
                        break;
                    case 'first-exchange':
                        window.location.href = 'shop.html';
                        break;
                    case 'weekly-checkin':
                        // 检查连续签到状态
                        const days = parseInt(localStorage.getItem('consecutiveSignInDays') || '0');
                        if (days >= 7) {
                            // 发放奖励
                            userInfoData.points = (userInfoData.points || 0) + 50;
                            setUserInfo(userInfoData);
                            addPointsRecord(50, '连续签到7天奖励', 'gained');
                            updateUserDisplay();
                            updatePointsHistory();
                            showNotification('奖励发放', '恭喜您连续签到7天，获得50积分奖励', 'success');
                        } else {
                            showNotification('提示', `还需要连续签到 ${7 - days} 天才能获得奖励`, 'info');
                        }
                        break;
                    case 'invite-friends':
                        // 模拟生成邀请链接
                        const inviteLink = `${window.location.origin}${window.location.pathname}?invite=${userInfoData.id}`;
                        // 复制到剪贴板
                        navigator.clipboard.writeText(inviteLink).then(() => {
                            showNotification('复制成功', '邀请链接已复制到剪贴板', 'success');
                        }).catch(() => {
                            alert(`邀请链接：${inviteLink}`);
                        });
                        break;
                }
            });
        });

        // 检查用户登录状态
        function updateUserDisplay() {
            const userInfoData = getUserInfo();
            const notLoggedIn = document.getElementById('not-logged-in');
            const userPointsOverview = document.getElementById('user-points-overview');
            const userTotalPoints = document.getElementById('user-total-points');
            const availablePoints = document.getElementById('available-points');
            const usedPoints = document.getElementById('used-points');
            const expiredPoints = document.getElementById('expired-points');
            
            if (userInfoData) {
                // 用户已登录
                if (notLoggedIn) notLoggedIn.classList.add('hidden');
                if (userPointsOverview) userPointsOverview.classList.remove('hidden');
                if (userName) userName.textContent = userInfoData.username;
                if (userAvatar) userAvatar.src = userInfoData.avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${userInfoData.username}`;
                if (dropdownUsername) dropdownUsername.textContent = userInfoData.username;
                if (dropdownUserpoints) dropdownUserpoints.textContent = `积分: ${userInfoData.points || 0}`;
                if (avatarPlaceholder) avatarPlaceholder.innerHTML = `<img src="${userInfoData.avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${userInfoData.username}`}" alt="用户头像" class="w-full h-full rounded-full object-cover">`;
                
                // 更新积分显示
                const points = userInfoData.points || 0;
                if (userTotalPoints) userTotalPoints.textContent = points;
                if (availablePoints) availablePoints.textContent = points;
                
                // 模拟已用积分和即将过期积分
                const simulatedUsedPoints = Math.floor(points * 0.3);
                const simulatedExpiredPoints = Math.floor(points * 0.1);
                if (usedPoints) usedPoints.textContent = simulatedUsedPoints;
                if (expiredPoints) expiredPoints.textContent = simulatedExpiredPoints;
                
                // 更新签到状态
                const today = new Date().toDateString();
                const lastSignIn = localStorage.getItem('lastSignIn');
                const currentConsecutive = parseInt(localStorage.getItem('consecutiveSignInDays') || '0');
                
                if (signInStatus && signInBtn && consecutiveDays) {
                    if (lastSignIn === today) {
                        signInStatus.textContent = '今日已签到';
                        signInBtn.disabled = true;
                    } else {
                        signInStatus.textContent = '今日未签到';
                        signInBtn.disabled = false;
                    }
                    consecutiveDays.textContent = currentConsecutive;
                }
                
                // 更新积分明细弹窗数据
                if (historyModalTotalPoints) historyModalTotalPoints.textContent = points;
            } else {
                // 用户未登录
                if (notLoggedIn) notLoggedIn.classList.remove('hidden');
                if (userPointsOverview) userPointsOverview.classList.add('hidden');
                if (userName) userName.textContent = '登录/注册';
                if (avatarPlaceholder) avatarPlaceholder.innerHTML = '<i class="fa fa-user text-gray-500"></i>';
            }
        }

        // 更新积分明细
        function updatePointsHistory(filter = 'all') {
            const userInfoData = getUserInfo();
            if (userInfoData) {
                const pointsHistory = getPointsHistory() || [];
                
                // 过滤积分记录
                let filteredHistory = pointsHistory;
                if (filter === 'gained') {
                    filteredHistory = pointsHistory.filter(record => record.type === 'gained');
                } else if (filter === 'used') {
                    filteredHistory = pointsHistory.filter(record => record.type === 'used');
                }
                
                // 按时间排序
                filteredHistory.sort((a, b) => new Date(b.date) - new Date(a.date));
                
                // 清空列表
                if (pointsHistoryList) {
                    pointsHistoryList.innerHTML = '';
                    
                    if (filteredHistory.length === 0) {
                        const emptyState = document.createElement('div');
                        emptyState.className = 'text-center py-10';
                        emptyState.innerHTML = `
                            <i class="fa fa-history text-gray-300 text-4xl mb-2"></i>
                            <p class="text-gray-500">暂无积分记录</p>
                        `;
                        pointsHistoryList.appendChild(emptyState);
                    } else {
                        // 按日期分组
                        const groupedHistory = {};
                        filteredHistory.forEach(record => {
                            const date = new Date(record.date).toLocaleDateString('zh-CN');
                            if (!groupedHistory[date]) {
                                groupedHistory[date] = [];
                            }
                            groupedHistory[date].push(record);
                        });
                        
                        // 创建分组显示
                        Object.entries(groupedHistory).forEach(([date, records]) => {
                            // 日期标题
                            const dateHeader = document.createElement('div');
                            dateHeader.className = 'text-sm font-medium text-gray-500 mb-2';
                            dateHeader.textContent = date;
                            pointsHistoryList.appendChild(dateHeader);
                            
                            // 记录列表
                            records.forEach(record => {
                                const recordItem = document.createElement('div');
                                recordItem.className = 'bg-gray-50 rounded-lg p-3 mb-2';
                                const pointsClass = record.type === 'gained' ? 'text-success' : 'text-danger';
                                const pointsSign = record.type === 'gained' ? '+' : '-';
                                
                                recordItem.innerHTML = `
                                    <div class="flex justify-between items-center">
                                        <div class="flex items-center space-x-2">
                                            <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                                                <i class="fa fa-${record.type === 'gained' ? 'plus' : 'minus'}-circle"></i>
                                            </div>
                                            <div>
                                                <p class="font-medium">${record.description}</p>
                                                <p class="text-xs text-gray-500">${new Date(record.date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</p>
                                            </div>
                                        </div>
                                        <span class="font-bold ${pointsClass}">${pointsSign}${record.points}</span>
                                    </div>
                                `;
                                pointsHistoryList.appendChild(recordItem);
                            });
                        });
                    }
                }
                
                // 计算本月获得和使用的积分
                const currentMonth = new Date().getMonth();
                const currentYear = new Date().getFullYear();
                
                let monthlyGained = 0;
                let monthlyUsed = 0;
                
                pointsHistory.forEach(record => {
                    const recordDate = new Date(record.date);
                    if (recordDate.getMonth() === currentMonth && recordDate.getFullYear() === currentYear) {
                        if (record.type === 'gained') {
                            monthlyGained += record.points;
                        } else {
                            monthlyUsed += record.points;
                        }
                    }
                });
                
                if (historyModalMonthlyGained) historyModalMonthlyGained.textContent = monthlyGained;
                if (historyModalMonthlyUsed) historyModalMonthlyUsed.textContent = monthlyUsed;
            }
        }

        // 更新购物车显示
        function updateCartDisplay() {
            try {
                const cartData = getCart() || [];
                const cartCount = document.getElementById('cart-count');
                const cartItemsList = document.getElementById('cart-items-list');
                const cartEmpty = document.getElementById('cart-empty');
                const cartItemsCount = document.getElementById('cart-items-count');
                const cartTotalPoints = document.getElementById('cart-total-points');
                const checkoutBtn = document.getElementById('checkout-btn');
                
                // 更新购物车数量标记
                if (cartCount) {
                    cartCount.textContent = cartData.length;
                    if (cartData.length === 0) {
                        cartCount.classList.add('hidden');
                    } else {
                        cartCount.classList.remove('hidden');
                    }
                }
                
                // 更新购物车内容
                if (cartItemsList && cartEmpty && cartItemsCount && cartTotalPoints && checkoutBtn) {
                    if (cartData.length === 0) {
                        cartItemsList.classList.add('hidden');
                        cartEmpty.classList.remove('hidden');
                        cartItemsCount.textContent = 0;
                        cartTotalPoints.textContent = 0;
                        checkoutBtn.disabled = true;
                    } else {
                        cartItemsList.classList.remove('hidden');
                        cartEmpty.classList.add('hidden');
                        
                        // 清空购物车列表
                        cartItemsList.innerHTML = '';
                        
                        let totalPoints = 0;
                        
                        // 添加购物车商品
                        cartData.forEach(item => {
                            totalPoints += item.points * item.quantity;
                            
                            const cartItem = document.createElement('div');
                            cartItem.className = 'flex items-start border-b pb-4';
                            cartItem.innerHTML = `
                                <img src="${item.image || 'default-avatar.svg'}" alt="${item.name || '商品'}" class="w-20 h-20 object-cover rounded-lg">
                                <div class="ml-3 flex-1">
                                    <h4 class="font-medium text-dark line-clamp-1">${item.name || '未知商品'}</h4>
                                    <p class="text-gray-500 text-xs mt-1">积分: <span class="text-primary font-medium">${item.points || 0}</span></p>
                                    <div class="flex items-center justify-between mt-2">
                                        <div class="flex items-center border rounded">
                                            <button class="decrease-quantity px-2 py-1 text-gray-500 hover:text-dark" data-id="${item.id}">-</button>
                                            <span class="px-2 py-1 min-w-8 text-center">${item.quantity || 1}</span>
                                            <button class="increase-quantity px-2 py-1 text-gray-500 hover:text-dark" data-id="${item.id}">+</button>
                                        </div>
                                        <button class="remove-from-cart text-danger hover:text-danger/80" data-id="${item.id}">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            `;
                            
                            cartItemsList.appendChild(cartItem);
                        });
                        
                        // 更新数量和总价
                        cartItemsCount.textContent = cartData.reduce((sum, item) => sum + (item.quantity || 1), 0);
                        cartTotalPoints.textContent = totalPoints;
                        
                        // 检查是否可以结算
                        checkoutBtn.disabled = !getUserInfo();
                        
                        // 如果用户未登录，更新结算按钮文本
                        if (!getUserInfo()) {
                            checkoutBtn.textContent = '请先登录';
                        } else {
                            checkoutBtn.textContent = '去结算';
                        }
                        
                        // 为购物车内的按钮绑定事件
                        document.querySelectorAll('.decrease-quantity').forEach(btn => {
                            btn.addEventListener('click', function() {
                                const productId = this.getAttribute('data-id');
                                decreaseQuantity(productId);
                                updateCartDisplay();
                            });
                        });
                        
                        document.querySelectorAll('.increase-quantity').forEach(btn => {
                            btn.addEventListener('click', function() {
                                const productId = this.getAttribute('data-id');
                                increaseQuantity(productId);
                                updateCartDisplay();
                            });
                        });
                        
                        document.querySelectorAll('.remove-from-cart').forEach(btn => {
                            btn.addEventListener('click', function() {
                                const productId = this.getAttribute('data-id');
                                removeFromCart(productId);
                                updateCartDisplay();
                                showNotification('移除成功', '已从购物车移除商品', 'info');
                            });
                        });
                    }
                }
            } catch (error) {
                console.error('更新购物车显示时出错:', error);
            }
        }

        // 去结算 - 避免变量重复声明
        const checkoutBtnElement = document.getElementById('checkout-btn');
        if (checkoutBtnElement) {
            checkoutBtnElement.addEventListener('click', () => {
                try {
                    const userInfoData = getUserInfo();
                    if (userInfoData && Object.keys(userInfoData).length > 1) { // 确保不是默认的空对象
                        window.location.href = 'shop.html';
                    } else {
                        window.location.href = 'login.html';
                    }
                } catch (error) {
                    console.error('结算时出错:', error);
                }
            });
        }

        // 确保updateUserDisplay函数在调用前定义
        function updateUserDisplay() {
            try {
                const userInfoData = getUserInfo() || {};
                const notLoggedIn = document.getElementById('not-logged-in');
                const userPointsOverview = document.getElementById('user-points-overview');
                const userName = document.getElementById('user-name');
                const avatarPlaceholder = document.getElementById('avatar-placeholder');
                const userAvatar = document.getElementById('user-avatar');
                const dropdownUsername = document.getElementById('dropdown-username');
                const dropdownUserpoints = document.getElementById('dropdown-userpoints');
                const userTotalPoints = document.getElementById('user-total-points');
                const availablePoints = document.getElementById('available-points');
                const usedPoints = document.getElementById('used-points');
                const expiredPoints = document.getElementById('expired-points');
                const signInStatus = document.getElementById('sign-in-status');
                const signInBtn = document.getElementById('sign-in-btn');
                const consecutiveDays = document.getElementById('consecutive-days');
                const historyModalTotalPoints = document.getElementById('history-modal-total-points');
                
                if (Object.keys(userInfoData).length > 1) { // 确保不是默认的空对象
                    // 用户已登录
                    if (notLoggedIn) notLoggedIn.classList.add('hidden');
                    if (userPointsOverview) userPointsOverview.classList.remove('hidden');
                    if (userName) userName.textContent = userInfoData.username || '用户';
                    
                    // 更新头像显示
                    if (userAvatar) userAvatar.src = userInfoData.avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${userInfoData.username || 'user'}`;
                    if (dropdownUsername) dropdownUsername.textContent = userInfoData.username || '用户';
                    if (dropdownUserpoints) dropdownUserpoints.textContent = `积分: ${userInfoData.points || 0}`;
                    if (avatarPlaceholder) avatarPlaceholder.innerHTML = `<img src="${userInfoData.avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${userInfoData.username || 'user'}`}" alt="用户头像" class="w-full h-full rounded-full object-cover">`;
                    
                    // 更新积分显示
                    const points = userInfoData.points || 0;
                    if (userTotalPoints) userTotalPoints.textContent = points;
                    if (availablePoints) availablePoints.textContent = points;
                    
                    // 模拟已用积分和即将过期积分
                    const simulatedUsedPoints = Math.floor(points * 0.3);
                    const simulatedExpiredPoints = Math.floor(points * 0.1);
                    if (usedPoints) usedPoints.textContent = simulatedUsedPoints;
                    if (expiredPoints) expiredPoints.textContent = simulatedExpiredPoints;
                    
                    // 更新签到状态
                    const today = new Date().toDateString();
                    const lastSignIn = localStorage.getItem('lastSignIn');
                    const currentConsecutive = parseInt(localStorage.getItem('consecutiveSignInDays') || '0');
                    
                    if (signInStatus && signInBtn && consecutiveDays) {
                        if (lastSignIn === today) {
                            signInStatus.textContent = '今日已签到';
                            signInBtn.disabled = true;
                        } else {
                            signInStatus.textContent = '今日未签到';
                            signInBtn.disabled = false;
                        }
                        consecutiveDays.textContent = currentConsecutive;
                    }
                    
                    // 更新积分明细弹窗数据
                    if (historyModalTotalPoints) historyModalTotalPoints.textContent = points;
                } else {
                    // 用户未登录
                    if (notLoggedIn) notLoggedIn.classList.remove('hidden');
                    if (userPointsOverview) userPointsOverview.classList.add('hidden');
                    if (userName) userName.textContent = '登录/注册';
                    if (avatarPlaceholder) avatarPlaceholder.innerHTML = '<i class="fa fa-user text-gray-500"></i>';
                }
            } catch (error) {
                console.error('更新用户显示时出错:', error);
            }
        }
        
        // 页面加载时初始化
        window.addEventListener('DOMContentLoaded', () => {
            try {
                // 更新用户显示
                updateUserDisplay();
                
                // 更新购物车显示
                updateCartDisplay();
            } catch (error) {
                console.error('页面初始化时出错:', error);
            }
        });

        // 积分充值和兑换功能 - 确保在使用前定义元素引用
        const pointsRechargeBtn = document.getElementById('points-recharge-btn');
        const pointsExchangeBtn = document.getElementById('points-exchange-btn');
        const rechargeModal = document.getElementById('recharge-modal');
        const exchangeModal = document.getElementById('exchange-modal');
        const closeRechargeModal = document.getElementById('close-recharge-modal');
        const closeExchangeModal = document.getElementById('close-exchange-modal');
        const rechargePointsInput = document.getElementById('recharge-points-input');
        const exchangePointsInput = document.getElementById('exchange-points-input');
        const currentPointsText = document.getElementById('current-points');
        const afterOperationPointsText = document.getElementById('after-operation-points');
        const confirmRechargeBtn = document.getElementById('confirm-recharge-btn');
        const confirmExchangeBtn = document.getElementById('confirm-exchange-btn');
        const userTotalPointsElement = document.getElementById('user-total-points');
        
        // 确保updateUserPointsDisplay函数在所有调用前定义
        function updateUserPointsDisplay(points) {
            if (userTotalPointsElement) {
                userTotalPointsElement.textContent = points;
            }
            if (currentPointsText) {
                currentPointsText.textContent = points;
            }
        }
        
        // 获取用户信息
        function getUserInfo() {
            const userStr = localStorage.getItem('user');
            if (userStr) {
                return JSON.parse(userStr);
            }
            return { points: 0 };
        }
        
        // 更新用户积分显示
        function updateUserPointsDisplay(points) {
            if (userTotalPointsElement) {
                userTotalPointsElement.textContent = points;
            }
            if (currentPointsText) {
                currentPointsText.textContent = points;
            }
        }
        
        // 打开充值弹窗
        if (pointsRechargeBtn && rechargeModal && rechargePointsInput && afterOperationPointsText) {
            pointsRechargeBtn.addEventListener('click', function() {
                try {
                    const userInfo = getUserInfo() || { points: 0 };
                    updateUserPointsDisplay(userInfo.points || 0);
                    rechargePointsInput.value = '';
                    afterOperationPointsText.textContent = userInfo.points || 0;
                    rechargeModal.classList.remove('hidden');
                } catch (error) {
                    console.error('打开充值弹窗时出错:', error);
                }
            });
        }
        
        // 打开兑换弹窗
        if (pointsExchangeBtn && exchangeModal && exchangePointsInput && afterOperationPointsText) {
            pointsExchangeBtn.addEventListener('click', function() {
                try {
                    const userInfo = getUserInfo() || { points: 0 };
                    updateUserPointsDisplay(userInfo.points || 0);
                    exchangePointsInput.value = '';
                    afterOperationPointsText.textContent = userInfo.points || 0;
                    exchangeModal.classList.remove('hidden');
                } catch (error) {
                    console.error('打开兑换弹窗时出错:', error);
                }
            });
        }
        
        // 关闭充值弹窗
        if (closeRechargeModal && rechargeModal) {
            closeRechargeModal.addEventListener('click', function() {
                rechargeModal.classList.add('hidden');
            });
        }
        
        // 关闭兑换弹窗
        if (closeExchangeModal && exchangeModal) {
            closeExchangeModal.addEventListener('click', function() {
                exchangeModal.classList.add('hidden');
            });
        }
        
        // 点击弹窗外部关闭弹窗
        document.addEventListener('click', function(event) {
            if (event.target === rechargeModal) {
                rechargeModal.classList.add('hidden');
            } else if (event.target === exchangeModal) {
                exchangeModal.classList.add('hidden');
            }
        });
        
        // 充值积分输入变化时更新预览
        if (rechargePointsInput && afterOperationPointsText) {
            rechargePointsInput.addEventListener('input', function() {
                try {
                    const userInfo = getUserInfo() || { points: 0 };
                    const inputPoints = parseInt(rechargePointsInput.value) || 0;
                    const newPoints = (userInfo.points || 0) + inputPoints;
                    afterOperationPointsText.textContent = newPoints;
                } catch (error) {
                    console.error('更新充值预览时出错:', error);
                }
            });
        }
        
        // 兑换积分输入变化时更新预览
        if (exchangePointsInput && afterOperationPointsText) {
            exchangePointsInput.addEventListener('input', function() {
                try {
                    const userInfo = getUserInfo() || { points: 0 };
                    const inputPoints = parseInt(exchangePointsInput.value) || 0;
                    const newPoints = (userInfo.points || 0) - inputPoints;
                    afterOperationPointsText.textContent = Math.max(0, newPoints);
                } catch (error) {
                    console.error('更新兑换预览时出错:', error);
                }
            });
        }
        
        // 确认充值
        if (confirmRechargeBtn && rechargePointsInput && rechargeModal) {
            confirmRechargeBtn.addEventListener('click', function() {
                try {
                    const userInfo = getUserInfo() || { points: 0 };
                    const rechargePoints = parseInt(rechargePointsInput.value);
                    
                    if (isNaN(rechargePoints) || rechargePoints <= 0 || !Number.isInteger(rechargePoints)) {
                        alert('请输入有效的正整数积分数量');
                        return;
                    }
                    
                    // 更新用户积分
                    userInfo.points = (userInfo.points || 0) + rechargePoints;
                    setUserInfo(userInfo);
                    
                    // 更新显示
                    updateUserPointsDisplay(userInfo.points);
                    
                    // 关闭弹窗
                    rechargeModal.classList.add('hidden');
                    
                    // 提示成功
                    alert('积分充值成功！');
                } catch (error) {
                    console.error('充值积分时出错:', error);
                    alert('操作失败，请稍后重试');
                }
            });
        }
        
        // 确认兑换
        if (confirmExchangeBtn && exchangePointsInput && exchangeModal) {
            confirmExchangeBtn.addEventListener('click', function() {
                try {
                    const userInfo = getUserInfo() || { points: 0 };
                    const exchangePoints = parseInt(exchangePointsInput.value);
                    
                    if (isNaN(exchangePoints) || exchangePoints <= 0 || !Number.isInteger(exchangePoints)) {
                        alert('请输入有效的正整数积分数量');
                        return;
                    }
                    
                    // 检查积分是否足够
                    if ((userInfo.points || 0) < exchangePoints) {
                        alert('积分不足，无法完成兑换');
                        return;
                    }
                    
                    // 更新用户积分
                    userInfo.points = (userInfo.points || 0) - exchangePoints;
                    setUserInfo(userInfo);
                    
                    // 更新显示
                    updateUserPointsDisplay(userInfo.points);
                    
                    // 关闭弹窗
                    exchangeModal.classList.add('hidden');
                    
                    // 提示成功
                    alert('积分兑换成功！');
                } catch (error) {
                    console.error('兑换积分时出错:', error);
                    alert('操作失败，请稍后重试');
                }
            });
        }
        
        // 输入框只允许输入正整数
        if (rechargePointsInput) {
            rechargePointsInput.addEventListener('keypress', function(event) {
                if (!/\d/.test(event.key)) {
                    event.preventDefault();
                }
            });
        }
        
        if (exchangePointsInput) {
            exchangePointsInput.addEventListener('keypress', function(event) {
                if (!/\d/.test(event.key)) {
                    event.preventDefault();
                }
            });
        }
    </script>
</body>
</html>